/**
 * 性能优化器 - 主入口文件
 */

import { performanceMonitor, memoryManager } from './performance.js';

export class PerformanceOptimizer {
  constructor(options = {}) {
    this.options = {
      enableMonitoring: true,
      enableMemoryOptimization: true,
      autoCleanup: true,
      cleanupInterval: 60000, // 1分钟
      ...options
    };
    
    this.isInitialized = false;
    this.cleanupTimer = null;
    
    this.init();
  }
  
  // 初始化
  init() {
    if (this.isInitialized) return;
    
    try {
      // 初始化性能监控
      if (this.options.enableMonitoring) {
        performanceMonitor.start();
      }
      
      // 初始化内存管理
      if (this.options.enableMemoryOptimization) {
        memoryManager.start();
      }
      
      // 启动自动清理
      if (this.options.autoCleanup) {
        this.startAutoCleanup();
      }
      
      // 监听页面可见性变化
      this.setupVisibilityListener();
      
      // 监听内存警告
      this.setupMemoryWarningListener();
      
      this.isInitialized = true;
      console.log('Performance Optimizer initialized');
      
    } catch (error) {
      console.error('Performance Optimizer initialization error:', error);
    }
  }
  
  // 启动自动清理
  startAutoCleanup() {
    this.cleanupTimer = setInterval(() => {
      this.performCleanup();
    }, this.options.cleanupInterval);
  }
  
  // 执行清理
  performCleanup() {
    try {
      // 清理内存
      if (this.options.enableMemoryOptimization) {
        memoryManager.cleanup();
      }
      
      console.log('Performance cleanup completed');
      
    } catch (error) {
      console.error('Performance cleanup error:', error);
    }
  }
  
  // 设置页面可见性监听
  setupVisibilityListener() {
    if (typeof document === 'undefined') return;
    
    document.addEventListener('visibilitychange', () => {
      if (document.hidden) {
        this.onPageHidden();
      } else {
        this.onPageVisible();
      }
    });
  }
  
  // 页面隐藏时的处理
  onPageHidden() {
    // 清理内存
    if (this.options.enableMemoryOptimization) {
      memoryManager.cleanup();
    }
  }
  
  // 页面显示时的处理
  onPageVisible() {
    // 页面显示时的处理逻辑
    console.log('Page visible - performance optimization active');
  }
  
  // 设置内存警告监听
  setupMemoryWarningListener() {
    if (typeof window === 'undefined') return;
    
    // 监听内存警告（如果支持）
    if ('memory' in performance) {
      const checkMemory = () => {
        const memory = performance.memory;
        const usedRatio = memory.usedJSHeapSize / memory.jsHeapSizeLimit;
        
        if (usedRatio > 0.8) {
          console.warn('High memory usage detected:', usedRatio);
          this.handleMemoryWarning();
        }
      };
      
      setInterval(checkMemory, 30000); // 每30秒检查一次
    }
  }
  
  // 处理内存警告
  handleMemoryWarning() {
    // 清理内存
    memoryManager.cleanup();
    
    // 强制垃圾回收（如果支持）
    if (window.gc) {
      window.gc();
    }
    
    console.log('Memory warning handled - memory cleared');
  }
  
  // 获取性能报告
  getPerformanceReport() {
    const report = {
      timestamp: Date.now(),
      performance: performanceMonitor.getReport(),
      memory: memoryManager.getStats()
    };
    
    return report;
  }
  
  // 导出性能数据
  exportPerformanceData() {
    const report = this.getPerformanceReport();
    const dataStr = JSON.stringify(report, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `performance-report-${Date.now()}.json`;
    link.click();
    
    URL.revokeObjectURL(url);
  }
  
  // 重置所有统计
  resetStats() {
    performanceMonitor.reset();
    memoryManager.reset();
  }
  
  // 销毁优化器
  destroy() {
    if (this.cleanupTimer) {
      clearInterval(this.cleanupTimer);
      this.cleanupTimer = null;
    }
    
    // 停止所有管理器
    performanceMonitor.stop();
    memoryManager.stop();
    
    this.isInitialized = false;
    console.log('Performance Optimizer destroyed');
  }
}

// 创建全局实例
export const performanceOptimizer = new PerformanceOptimizer();

// 全局注册
if (typeof window !== 'undefined') {
  window.performanceOptimizer = performanceOptimizer;
  
  // 添加调试方法
  window.getPerformanceReport = () => performanceOptimizer.getPerformanceReport();
  window.exportPerformanceData = () => performanceOptimizer.exportPerformanceData();
  window.resetPerformanceStats = () => performanceOptimizer.resetStats();
}

// 导出所有管理器
export {
  performanceMonitor,
  memoryManager
};

// 默认导出
export default performanceOptimizer;